{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# LOGISTIC REGRESSION WITH MNIST"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PACKAGES LOADED\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "print (\"PACKAGES LOADED\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# DOWNLOAD AND EXTRACT MNIST DATASET"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data/train-images-idx3-ubyte.gz\n",
      "Extracting data/train-labels-idx1-ubyte.gz\n",
      "Extracting data/t10k-images-idx3-ubyte.gz\n",
      "Extracting data/t10k-labels-idx1-ubyte.gz\n",
      "MNIST loaded\n"
     ]
    }
   ],
   "source": [
    "mnist      = input_data.read_data_sets('data/', one_hot=True)\n",
    "trainimg   = mnist.train.images\n",
    "trainlabel = mnist.train.labels\n",
    "testimg    = mnist.test.images\n",
    "testlabel  = mnist.test.labels\n",
    "print (\"MNIST loaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## CREATE TENSOR GRAPH FOR LOGISTIC REGRESSION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "x = tf.placeholder(\"float\", [None, 784]) \n",
    "y = tf.placeholder(\"float\", [None, 10])  # None is for infinite \n",
    "W = tf.Variable(tf.zeros([784, 10]))\n",
    "b = tf.Variable(tf.zeros([10]))\n",
    "# LOGISTIC REGRESSION MODEL\n",
    "actv = tf.nn.softmax(tf.matmul(x, W) + b) \n",
    "# COST FUNCTION\n",
    "cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv), reduction_indices=1)) \n",
    "# OPTIMIZER\n",
    "learning_rate = 0.01\n",
    "optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## PREDICTION AND ACCURACY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# PREDICTION\n",
    "pred = tf.equal(tf.argmax(actv, 1), tf.argmax(y, 1))    \n",
    "# ACCURACY\n",
    "accr = tf.reduce_mean(tf.cast(pred, \"float\"))\n",
    "# INITIALIZER\n",
    "init = tf.initialize_all_variables()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# TRAIN MODEL"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 000/050 cost: 1.176559254 train_acc: 0.870 test_acc: 0.852\n",
      "Epoch: 005/050 cost: 0.440937506 train_acc: 0.930 test_acc: 0.895\n",
      "Epoch: 010/050 cost: 0.383336526 train_acc: 0.900 test_acc: 0.904\n",
      "Epoch: 015/050 cost: 0.357268913 train_acc: 0.880 test_acc: 0.909\n",
      "Epoch: 020/050 cost: 0.341493352 train_acc: 0.970 test_acc: 0.912\n",
      "Epoch: 025/050 cost: 0.330508839 train_acc: 0.890 test_acc: 0.914\n",
      "Epoch: 030/050 cost: 0.322364672 train_acc: 0.880 test_acc: 0.916\n",
      "Epoch: 035/050 cost: 0.315942195 train_acc: 0.960 test_acc: 0.917\n",
      "Epoch: 040/050 cost: 0.310731307 train_acc: 0.910 test_acc: 0.918\n",
      "Epoch: 045/050 cost: 0.306349064 train_acc: 0.970 test_acc: 0.919\n",
      "DONE\n"
     ]
    }
   ],
   "source": [
    "training_epochs = 50\n",
    "batch_size      = 100\n",
    "display_step    = 5\n",
    "# SESSION\n",
    "sess = tf.Session()\n",
    "sess.run(init)\n",
    "# MINI-BATCH LEARNING\n",
    "for epoch in range(training_epochs):\n",
    "    avg_cost = 0.\n",
    "    num_batch = int(mnist.train.num_examples/batch_size)\n",
    "    for i in range(num_batch): \n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "        sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})\n",
    "        feeds = {x: batch_xs, y: batch_ys}\n",
    "        avg_cost += sess.run(cost, feed_dict=feeds)/num_batch\n",
    "    # DISPLAY\n",
    "    if epoch % display_step == 0:\n",
    "        feeds_train = {x: batch_xs, y: batch_ys}\n",
    "        feeds_test = {x: mnist.test.images, y: mnist.test.labels}\n",
    "        train_acc = sess.run(accr, feed_dict=feeds_train)\n",
    "        test_acc = sess.run(accr, feed_dict=feeds_test)\n",
    "        print (\"Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f\" \n",
    "               % (epoch, training_epochs, avg_cost, train_acc, test_acc))\n",
    "print (\"DONE\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
